package controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import model.BookmarkDAO;
import model.Model;

import org.mybeans.dao.DAOException;
import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

import beans.Bookmark;
import beans.User;

import formbeans.BookmarkForm;
import formbeans.ChangePwdForm;

/*
 *  Course: S09-15437 - WEB APPLICATION DEVELOPMENT 
 * 	Name: Jiale Huang
 * 	Andrew ID: jialeh
 * 	Date: 2/23/2009
 *  Assignment: Hw4
 */


public class AddBookmarkAction extends Action{

	private FormBeanFactory<BookmarkForm> formBeanFactory = FormBeanFactory.getInstance(BookmarkForm.class);
	
	private BookmarkDAO bookmarkDAO;
	
	public AddBookmarkAction(Model model){
		
		bookmarkDAO = model.getBookmarkDAO();
	}
	
	@Override
	public String getName() {
		return "addBookmark.do";
	}

	@Override
	public String perform(HttpServletRequest request) {
		
        List<String> errors = new ArrayList<String>();
        request.getSession().setAttribute("aerrors",errors);
		
        // Load the form parameters into a form bean
		BookmarkForm form;
		try {
			form = formBeanFactory.create(request);
		
			
	        // If no params were passed, return with no errors so that the form will be
	        // presented (we assume for the first time).
			if(!form.isPresent()){
				String webapp = request.getContextPath();
				return webapp + "/manage.do";
			}
				
	        // Check for any validation errors
	        errors.addAll(form.getValidationErrors());
	        if (errors.size() != 0) {
				String webapp = request.getContextPath();
				return webapp + "/manage.do";
	        }
	    

			User user = (User) request.getSession().getAttribute("user");
			
			if(user != null){
				
				Bookmark bookmark = new Bookmark(user.getUserEmail());
				
				bookmark.setURL(form.getURL());
				bookmark.setComment(form.getComment());
				bookmark.setClickCount(0);
				

				bookmark = bookmarkDAO.create(bookmark);

				
				String webapp = request.getContextPath();
				return webapp + "/manage.do";
			}else{
				
				return "login.jsp";
			}
		}catch (DAOException e) {
			errors.add(e.toString());
			String webapp = request.getContextPath();
			return webapp + "/manage.do";
		} catch (FormBeanException e) {
			errors.add(e.toString());
			String webapp = request.getContextPath();
			return webapp + "/manage.do";
		}
	}

}
